//
//  UINavigationController+JwCate.m
//  JwPack
//
//  Created by 陈警卫 on 2024-07-25.
//

#import "UINavigationController+JwCate.h"
#import "JwScreen.h"

@implementation UINavigationController (JwCate)

/// 最前导航控制器
+ (UINavigationController *)jw_frontNC {
    UIViewController *vc = [JwScreen window].rootViewController;
    return [self jw_frontNCFromVC:vc];
}

/// 最前导航控制器
+ (UINavigationController *)jw_frontNCFromVC:(UIViewController *)vc {
    if ([vc isKindOfClass:[UITabBarController class]]) {
        UINavigationController *nc = ((UITabBarController *)vc).selectedViewController;
        return [self jw_frontNCFromVC:nc];
    } else if ([vc isKindOfClass:[UINavigationController class]]) {
        if (((UINavigationController *)vc).presentedViewController) {
            return [self jw_frontNCFromVC:((UINavigationController *)vc).presentedViewController];
        }
        return [self jw_frontNCFromVC:((UINavigationController *)vc).topViewController];
    } else if ([vc isKindOfClass:[UIViewController class]]) {
        if (vc.presentedViewController) {
            return [self jw_frontNCFromVC:vc.presentedViewController];
        } else {
            return vc.navigationController;
        }
    } else {
        return nil;
    }
}

/// 获取已经push的控制器
- (UIViewController *)jw_pushVCWithName:(NSString *)name {
    for (UIViewController *controller in self.viewControllers) {
        if ([controller isKindOfClass:NSClassFromString(name)]) {
            return controller;
        }
    }
    return nil;
}

@end
